<?php
/*
 * Created on 2010-8-13
 *	Author HCB
 */

class Mysql {
	
	private $conn;
	
	public function __construct(){
		$this->connect();
	}
	
	// 连接数据库
	public function connect() {
		if ( !defined('DB_CONN') ){
			$this->conn = mysql_pconnect ( DB_HOST, DB_USER, DB_PASS ) or die ( 'could not connect mysql!' );
			mysql_select_db ( DB_DATABASE, $this->conn );
			$this->err();
			mysql_query( 'set names '.DB_CHARSET );
			
			define('DB_CONN', $this->conn);
		}else{
			$this->conn = DB_CONN;
		}
	}
	
	/**
	 * 向数据库发出请求
	 * @param string $sql
	 * @return boolean
	 * */
	public function query( $sql ) {
		$query_ret = mysql_query( $sql, $this->conn );
		$this->err();
		return $query_ret;
	}
	
	/**
	 * 从数据库取出多条数据
	 * @param string $sql_or_table sql或表名
	 * @param string $where 当$sql_or_table为表名时的限制条件
	 * @param string $col 当$sql_or_table为表名时的要选取的字段
	 * */
	public function getAll( $sql_or_table, $where = '', $col = '*', $order = '' ) {
		if( $where ){
			$sql = "SELECT {$col} FROM `".DB_TABLE_PRE.$sql_or_table."` WHERE {$where}".( $order ? " ORDER BY {$order}" : "");
		}else{
			$sql = $sql_or_table;
		}
		
		$query_ret= $this->query( $sql );
		$rows = array ();
		while( $row = mysql_fetch_assoc( $query_ret ) ) {
			$rows[] = $row;
		}
		$this->freeResult( $query_ret);
		$this->err();
		return $rows;
	}
	
	/**
	 * 从数据库取出一条数据
	 * @param string $sql_or_table sql或表名
	 * @param string $where 当$sql_or_table为表名时的限制条件
	 * @param string $col 当$sql_or_table为表名时的要选取的字段
	 * @return array
	 * */
	public function getOne( $sql_or_table, $where = '', $col = '*' ) {
		if( $where ){
			$sql = "SELECT {$col} FROM `".DB_TABLE_PRE.$sql_or_table."` WHERE {$where} LIMIT 1";
		}else{
			$sql = $sql_or_table;
		}
	
		$query_ret = $this->query( $sql );
		$ret = mysql_fetch_assoc( $query_ret );
		$this->freeResult( $query_ret );
		$this->err();
		return $ret;
	}
	
	/**
	 * 获得总记录数
	 * @param string $table 表名
	 * @param string $where 条件
	 * @param string $sql 特殊情况下用此sql
	 * @param integer
	 * */
	function getCount($table, $where = '', $sql = '') {
		if( $where ) $where = " WHERE {$where}";
		if( empty ( $sql ) ) $sql = "SELECT COUNT(1) AS num FROM `".DB_TABLE_PRE.$table."` {$where}";
		$ret = $this->getOne( $sql );
		return $ret ['num'];
	}
	
	/**
	 * 在使用SQL_CALC_FOUND_ROWS 后调用，取得无limit限制的记录数
	 * */
	function getNum(){
		$ret = mysql_fetch_assoc( $this->query("SELECT FOUND_ROWS() num") );
		return $ret['num'];
	}
	
	/**
	 * 插入数据
	 * @param string $table 表名
	 * @param array $arr 键名为字段名，键值为字段值
	 * @param integer $n 数组维数
	 * @return integer 最后插入记录的ID
	 * */
	public function insert($table, $arr, $n = 1) {	
		if( $n == 1 ){
			$filed = implode( "`,`", array_keys( $arr ) );
			$value = implode( "','", array_values( $arr ) );
			$sql = "INSERT INTO `".DB_TABLE_PRE.$table."` (`{$filed}` ) VALUES( '{$value}' )";
		}elseif( $n == 2 ){
			$filed = implode( "`,`", array_keys( $arr[0] ) );
			foreach( $arr as $v ){
				$vs[] = implode( "','", array_values( $v ) );
			}
			$value = implode( "'),('", $vs );
			$sql = "INSERT INTO `".DB_TABLE_PRE.$table."` (`{$filed}` ) VALUES( '{$value}' )";
		}

		$this->query ( $sql );
		$ret = mysql_insert_id ( $this->conn );
		$this->err ();
		return $ret;
	}
	
	/**
	 * 替换数据
	 * @param string $table 表名
	 * @param array $arr 键名为字段名，键值为字段值
	 * @return integer 最后插入记录的ID
	 * */
	public function replace($table, $arr) {
	
		$filed = implode( "`,`", array_keys( $arr ) );
		$value = implode( "','", array_values( $arr ) );
		
		$sql = "REPLACE INTO `".DB_TABLE_PRE.$table."` ( `{$filed}` ) VALUES( '{$value}' )";
		$this->query ( $sql );
		$id = mysql_insert_id ( $this->conn );
		$this->err();
		return $id;
	}
	
	/**
	 * 更新键值对型表格
	 * 表格中只有两个字段：key,value	key为主键
	 * @param string $table 表名
	 * @param array $arr 键名为字段名，键值为字段值
	 * */
	public function update_k_v($table, $arr){
		foreach( $arr as $k=>$v ){
			$this->replace($table,array('key'=>$k,'value'=>$v));
		}
		return true;
	}
	
	/**
	 * 更新数据
	 * @param string $table 表名
	 * @param array $arr 键名为字段名，键值为字段值
	 * @param string $where 更新条件
	 * @param boolean
	 * */
	public function update($table, $arr, $where) {
		if( !$where ) return 'no value for where!';
		$str = $commat = '';
		foreach ( $arr as $k => $v ) {
			$str .= $commat ."`". $k . "`='" .$v. "'";
			$commat = ',';
		}
		$sql = "UPDATE `".DB_TABLE_PRE.$table."` SET {$str} WHERE {$where}";
		return $this->query ( $sql );
	
	}
	function fetch_array($query, $result_type = MYSQL_ASSOC)
    {
        return mysql_fetch_array($query, $result_type);
    }
	
	/**
	 * 删除数据
	 * @param string $table 表名
	 * @param string $where 删除条件
	 * @return boolean
	 * */
	public function delete($table, $where) {
		$sql = "DELETE FROM `".DB_TABLE_PRE.$table."` WHERE {$where}";
		return $this->query ( $sql );
	}
	
	//关闭数据库
	public function close() {
		mysql_close ( $this->conn );
		$this->err ();
	}
	
	//释放请求资源
	public function freeResult( $query ) {
		return mysql_free_result ( $query );
	}

	/**
	 * 调试模式下输出mysql错误
	 * */
	private function err() {
		if( DB_DEBUG ) echo mysql_error ();
	}

	
}
?>
